package com.dobbyspringside.examples.quickstart.service.task;

import com.dobbyspringside.examples.quickstart.entity.Task;
import com.dobbyspringside.examples.quickstart.repository.TaskDao;
import com.dobbyspringside.modules.persistence.DynamicSpecifications;
import com.dobbyspringside.modules.persistence.SearchFilter;
import org.hibernate.cfg.beanvalidation.GroupsPerOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
import sun.security.util.DisabledAlgorithmConstraints;

import javax.transaction.Transactional;
import java.util.List;
import java.util.Map;

/**
 * Created by liguoqing on 2016/2/16.
 */
// Spring Bean的标识.
@Component
// 类中所有public函数都纳入事务管理的标识.
@Transactional
public class TaskService {

    @Autowired
    private TaskDao taskDao;


    public Task getTask(Long id) {
        return taskDao.findOne(id);
    }

    public void saveTask(Task entity) {
        taskDao.save(entity);
    }

    public void deleteTask(Long id) {
        taskDao.delete(id);
    }

    public List<Task> getAllTask() {
        return (List<Task>) taskDao.findAll();
    }

    public Page<Task> getUserTask(Long userId, Map<String,Object> searchParams,int pageNumber,int pageSize,String sortType) {
        PageRequest pageRequest = buildPageRequest(pageNumber,pageSize,sortType);
        Specification<Task> taskSpecification = buildSpecification(userId,searchParams);
        return taskDao.findAll(taskSpecification,pageRequest);
    }


    /**
     * 创建分页请求
     */
    private PageRequest buildPageRequest(int pageNumber, int pageSize, String sortType) {
        Sort sort = null;
        if("auto".equals(sortType)) {
            sort = new Sort(Sort.Direction.ASC, "id");
        } else if("title".equals(sortType)) {
            sort = new Sort(Sort.Direction.ASC, "title");
        }
        return new PageRequest(pageNumber-1,pageSize,sort);
    }

    /**
     * 创建动态查询条件组合.
     */
    private Specification<Task> buildSpecification(Long userId, Map<String, Object> searchParams) {
        Map<String,SearchFilter> filter = SearchFilter.parse(searchParams);
        filter.put("user.id", new SearchFilter("user.id", SearchFilter.Operator.EQ,userId));
        Specification<Task> taskSpecification = DynamicSpecifications.bySearchFilter(filter.values(), Task.class);
        return taskSpecification;
    }
}
